//
//  HJQRCodeController.m
//  newOcWeibo
//
//  Created by heJing on 15/7/21.
//  Copyright © 2015年 heima. All rights reserved.
//

#import "HJQRCodeController.h"
#import <AVFoundation/AVFoundation.h>

@interface HJQRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>

- (IBAction)close:(id)sender;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCons;

@property(nonatomic, strong)CADisplayLink *link;

// 会话
@property (nonatomic, strong) AVCaptureSession *session;


@end

@implementation HJQRCodeController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
 
    [self.link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];

    self.link = link;
    
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    
    // 1. 获取输入设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2. 根据输入设备创建输入对象
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    // 3. 创建输出对象
    AVCaptureMetadataOutput *outPut = [AVCaptureMetadataOutput new];
    
    // 4. 设置代理监听输出对象输出的数据
    [outPut setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 5. 创建会话（桥梁）
    AVCaptureSession *session = [AVCaptureSession new];
    
    // 6.添加输入和输出到会话中
    if ([session canAddInput:input]) {
        [session addInput:input];
    }
    if ([session canAddOutput:outPut]) {
        [session addOutput:outPut];
    }
    
    // 获取不到对象
    if (input == nil) {
        return;
    }
    
#warning 注意：设置输出对象能够理解解析的类型必须在输出对象添加到会话之后设置， 否则会报错
    // 7.告诉输出对象，需要输出什么样的数据（支持解析什么样的马）
    [outPut setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 8.创建预览图层
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    previewLayer.frame = self.view.frame;
    [self.view.layer insertSublayer:previewLayer atIndex:0];

    // 9.开始扫描数据
#warning 注意，扫描二维码是一个持久的操作，有可能很耗时间
    [session startRunning];
    self.session = session;
}


/**
 *  扫描到二维码之后会调用
 */
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        // 1. 停止扫描
        [self.session stopRunning];
        
        // 2. 停止冲击波
        [self.link removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        
        // 3. 取出扫描到的数据
        AVMetadataMachineReadableCodeObject *obj = [metadataObjects lastObject];
        
        HJLog(@"扫描到的数据是：%@",obj);
    }else{
    
        HJLog(@"毛都没扫到");
    }
}


-(void)update
{
    // 不停的修改顶部约束, 每次向下走1
    self.topCons.constant -= 1;
    if (self.topCons.constant <= -200) {
        // 如果超出显示范围, 就回到原来的起始位置
        self.topCons.constant = 200;
    }
    
}

- (IBAction)close:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
